package cn.demoncat.util.web.entity;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import java.io.IOException;

/**
 * 可重复读取的 ServletInputStream
 *
 * @author 延晓磊
 * @since 2023年02月08日
 */
public class RepeatableServletInputStream extends ServletInputStream {

    private byte[] body;
    private int lastIndex = -1;
    private ReadListener listener;

    public RepeatableServletInputStream(byte[] body) {
        this.body = body;
    }

    @Override
    public int read() throws IOException {
        if (isFinished()) {
            return -1;
        }
        int i = body[lastIndex + 1];
        lastIndex++;
        if (isFinished() && listener != null) {
            try {
                listener.onAllDataRead();
            } catch (IOException e) {
                listener.onError(e);
                throw e;
            }
        }
        return i;
    }

    @Override
    public boolean isFinished() {
        return lastIndex == body.length - 1;
    }

    @Override
    public boolean isReady() {
        return isFinished();
    }

    @Override
    public void setReadListener(ReadListener listener) {
        if (listener == null) {
            throw new IllegalArgumentException("listener cann not be null");
        }
        if (this.listener != null) {
            throw new IllegalArgumentException("listener has been set");
        }
        this.listener = listener;
        if (!isFinished()) {
            try {
                listener.onAllDataRead();
            } catch (IOException e) {
                listener.onError(e);
            }
        } else {
            try {
                listener.onAllDataRead();
            } catch (IOException e) {
                listener.onError(e);
            }
        }
    }

    @Override
    public int available() {
        return body.length - lastIndex - 1;
    }

    @Override
    public void close() {
        lastIndex = body.length - 1;
        body = null;
    }
}